package vh.android.multiconnector.library.model;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Channel {

	private static final long TIMEOUT = 5000L;

	// the creater's mac address
	private String mIP;

	// channel name
	private String mName;

	// passphrase to enter channel
	private String mPassphrase;

	private int mPort;

	private long mPing;

	public String getIP() {
		return mIP;
	}

	public void setIP(String pIP) {
		this.mIP = pIP;
	}

	public String getName() {
		return mName;
	}

	public void setName(String mName) {
		this.mName = mName;
	}

	public boolean isSecured() {
		return mPassphrase != null;
	}

	public void setPassphrase(String pPassphrase) {
		this.mPassphrase = pPassphrase;
	}

	public String getPassphrase() {
		return mPassphrase;
	}

	public boolean isCreater(String pIP) {
		return pIP.equalsIgnoreCase(getIP());
	}

	public void setPort(int pPort) {
		this.mPort = pPort;
	}

	public int getPort() {
		return mPort;
	}
	
	public String getChecksum() {
		return md5(mIP + mPort + mName).toLowerCase();
	}

	public static String md5(String in) {
		MessageDigest digest;
		try {
			digest = MessageDigest.getInstance("MD5");
			digest.reset();
			digest.update(in.getBytes());
			byte[] a = digest.digest();
			int len = a.length;
			StringBuilder sb = new StringBuilder(len << 1);
			for (int i = 0; i < len; i++) {
				sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
				sb.append(Character.forDigit(a[i] & 0x0f, 16));
			}
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void setPing(long pTimestamp) {
		this.mPing = pTimestamp;
	}
	
	public boolean isTimedout() {
		return System.currentTimeMillis() - getPing() > TIMEOUT;
	}
	
	public long getPing() {
		return mPing;
	}
}
